import axios from "axios";
import router from '../router';
import storage from './storage';
import type {AxiosRequestConfig} from "axios";

const instance = axios.create({
    withCredentials: false,
    baseURL: import.meta.env.VITE_API_URL,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})

instance.interceptors.request.use(config => {
    const token = storage.getItem('token', '')
    if (token) {
        config.headers.Authorization = 'Bearer '+token
    }
    return config
}, error => {
    return Promise.reject(error)
})

instance.interceptors.response.use(response => {
    if (response.data && response.data.code === 401) {
        logout()
    }
    return response.data
}, error => {
    if (error.response.status === 401) {
        logout()
    }else if (error.response.status === 503) {
        error.message = "服务正在维护中，请稍等片刻..."
    }
    return Promise.reject(error)
})

export default async function (config: AxiosRequestConfig): Promise<RequestResult> {
    const defaults = {
        method: 'GET',
        url: '',
        params: null,
        data: null,
        codes: [0],
        cache: true,
    }
    const options = Object.assign({}, defaults, config)
    if (options.method?.toUpperCase() === 'GET' || options.method?.toUpperCase() === 'DELETE') {
        if (!options.cache) {
            options.params = Object.assign({
                't': new Date().getTime()
            }, options.params)
        }
    }
    let result: RequestResult;
    try {
        result = await instance(options)
    } catch (e) {
        throw new Error('连接服务器失败')
    }

    if (!options.codes.includes(result.code)) {
        throw new Error(result.message)
    }

    return result
}

function logout() {
    storage.removeItem('token');
    router.push({name: 'login'})
}
